<template>
	<view class="brand">
		<uni-forms ref="brandRef" :modelValue="brandFormData" :rules="brandRules" :label-width="100"
			label-align="right">

			<uni-forms-item label="品牌图片">
				<uni-file-picker v-model="brandFormData.thumb" fileMediatype="image" mode="grid" :limit="1" />
			</uni-forms-item>

			<uni-forms-item label="品牌名称" name="name" required>
				<uni-easyinput type="text" v-model="brandFormData.name" placeholder="请输入品牌名称" />
			</uni-forms-item>

			<uni-forms-item label="商户电话" name="mobile" required>
				<uni-easyinput type="text" v-model="brandFormData.mobile" placeholder="请输入商户电话" />
			</uni-forms-item>

			<uni-forms-item label="商户地址" name="address">
				<uni-easyinput type="text" v-model="brandFormData.address" placeholder="请输入商户地址" />
			</uni-forms-item>

			<uni-forms-item label="商户简介" name="about">
				<uni-easyinput type="textarea" v-model="brandFormData.about" placeholder="请输入商户简介" />
			</uni-forms-item>

			<button type="primary" @click="onSubmit">提交</button>
		</uni-forms>
	</view>
</template>

<script>
	const brandCloudObj=uniCloud.importObject("mall-brand");
	export default {
		data() {
			return {
				brandFormData: {
					name: "",
					mobile: "",
					address: "",
					about: "",
					thumb: []
				},
				brandRules: {
					name: {
						rules: [{
								required: true,
								errorMessage: "请输入品牌名称"
							},
							{
								minLength: 3,
								maxLength: 10,
								errorMessage: '长度在 {minLength} 到 {maxLength} 个字符'
							}
						]
					},
					mobile: {
						rules: [{
								required: true,
								errorMessage: "请输入商户电话"
							},
							{
								validateFunction: function(rule, value, data, callback) {
									let res = /^1[3-9]\d{9}$/.test(value);
									if (!res) {
										callback("请输入正确的商户电话");
									}
									return;
								}
							}
						]
					}
				}
			};
		},
		onLoad() {
				this.getBrand();
		},
		methods: {
			onSubmit() {
				this.$refs.brandRef.validate().then(res => {
					let arr=this.brandFormData.thumb.map(item=>{
						return {
							extname:item.extname,
							url:item.url,
							name:item.name,
							size:item.size
						}
					})
					this.brandFormData.thumb=arr;
					
					this.addAndUpate();
				}).catch(err => {
					console.log(err);
				})
			},
			addAndUpate(){
				if(this.brandFormData._id){
					brandCloudObj.update(this.brandFormData).then(res=>{
						//uni.$u.toast("修改成功");
						uni.showToast({
							title:"修改成功",
							mask:true
						});
						setTimeout(()=>{
							uni.navigateBack();
						},1500)
					});
				}else{
					brandCloudObj.add(this.brandFormData).then(res=>{		
						uni.showToast({
							title:"添加成功"
						})
					});
				}
			},
			getBrand(){
				brandCloudObj.get().then(res=>{
					this.brandFormData=res.data[0];
				})
			}
			
			
		}
	}
</script>

<style lang="scss" scoped>
	.brand {
		padding: 30rpx;
	}
</style>